package mark.wxming.twotigershoplock.controller;

import mark.wxming.twotigershoplock.cache.api.LockApi;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * 关于redisson锁实现的基础接口可参考博客：
  https://blog.csdn.net/liuxiao723846/article/details/88131065
 * @author twotiger-wxm.
 * @date 2019/4/23.
 */
@RestController
@RequestMapping("/webReq/")
public class WebReqController {
    private static final Logger LOGGER = Logger.getLogger(WebReqController.class);

    @Autowired
    private LockApi lockApi;

    @RequestMapping("test")
    public String test(){
        //给同一个用户加锁
        String myLock = "addCart-"+"customerId"+"-"+"goodsId";
        Random rand = new Random();
        int num = rand.nextInt(1000);
        try {
            LOGGER.info("=========="+num+"==========请求来了");
            /**
             * long threadId = Thread.currentThread().getId();
             Long ttl = tryAcquire(leaseTime, unit, threadId);
             Redisson加锁时判断了线程，如果是同一个线程里同一个锁可以加多次，但是如果加了多个，解锁也需要解多个。否则多余的锁只能等待超时自己解锁。
             */
            lockApi.acquire(myLock);
            /*lockApi.acquire(myLock);
            lockApi.acquire(myLock);*/
            LOGGER.info("=========="+num+"==========加锁后执行业务代码");
        } finally {
            LOGGER.info("=========="+num+"==========去解锁了");
            lockApi.release(myLock);
            /*lockApi.release(myLock);
            lockApi.release(myLock);*/
            LOGGER.info("=========="+num+"==========解锁成功");
        }
        return "哈哈哈";
    }
}
